<template>
    <ElDialog 
    v-model="visible" 
    :title="'修改头像'" 
    :width="screenTypeWidth"
    :buttonText="'上传'"
    :submitBtnVisible="true"
    @handleClick="handleClick"
    @resetForm="resetForm">
        <template #main>
            <el-upload 
            class="avatar-uploader" 
            v-model:file-list="fileList"
            :auto-upload="false"
            :limit="1"
            :multiple="false"
            list-type="picture"
            :on-change="handleChange"
            drag
            accept="image/jpeg, image/jpg, image/png,">
                <el-icon class="el-icon--upload">
                    <upload-filled />
                </el-icon>
                <div class="el-upload__text">
                    拖拽上传 / 点击上传
                </div>
                <template #tip>
                    <div class="upload-tip">
                        仅支持jpg /jpeg /png格式，且一次一张，大小不能超过1MB
                    </div>
                </template>
            </el-upload>
        </template>
    </ElDialog>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import ElDialog from '@/components/system/el-dialog/el-dialog.vue';
import { storeToRefs } from 'pinia';
import { websiteStore } from '@/store/system/website';
const { screenType } = storeToRefs(websiteStore());
// ========================= 接收值 =========================
const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    },
});

// ========================= 计算属性 =========================
// 使用计算属性模拟双向绑定
const visible = computed({
    get() {
        return props.visible
    },
    set(value) {
        emit('update:visible', value)
    }
});

// 移动端适配
const screenTypeWidth = computed(() => {
    if(screenType.value === 'extraSmall-screen') {
        return '90%';
    }else if(screenType.value === 'small-screen') {
        return '70%';
    }else if(screenType.value === 'medium-screen') {
        return '42%';
    }else {
        return '30%';
    }
});

// ========================= 向父组件传值 =========================
let fileList = ref([]);             // 文件列表
const emit = defineEmits(['update:visible', 'handleClick']);
function handleClick() {            // 点击确定
    if(fileList.value.length !==0) {
        emit('handleClick', fileList.value[0].raw);
        emit('update:visible', false);
    }
};

// ========================= 上传文件的钩子函数 =========================
// 文件状态改变时的钩子
function handleChange(file, files) {
    const allowedTypes = ['image/jpeg', ' image/jpg', 'image/png'];
    const isAllowed = allowedTypes.includes(file.raw.type);
    if(!isAllowed) {
        ElMessage.error('仅支持jpg /jpeg /png图片格式');
        fileList.value = [];
    };
    if(file.size/1024/1024 > 1) {
        ElMessage.error('头像文件大小不能超过1MB');
        fileList.value = [];
    };
};

// 弹框关闭后
function resetForm() {
    fileList.value = [];
};
</script>

<style lang="scss" scoped>
    @import "./upload-avatar.scss";
</style>